﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using Microsoft.Practices.Prism.Mvvm;
using Microsoft.Practices.Prism.Logging;
using Microsoft.Practices.Unity;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.Net;
using Interfaces;
using Utility;

namespace Services
{
    [DataContract]
    [KnownType(typeof(NewsResult))]
    public class NewsResults : INotifyPropertyChanged, INewsResults
    {
        [DataMember]
        public ObservableCollection<INewsResult> Values { get { return _values; } set { _values = value; NotifyPropertyChanged("Values"); } }

        public event PropertyChangedEventHandler PropertyChanged;
        
        private ObservableCollection<INewsResult> _values;
        //private readonly ILoggerFacade _logger;
        private readonly IUnityContainer _container;

        public NewsResults(IUnityContainer container)//ILoggerFacade logger, IUnityContainer container)
        {
            _container = container;
            //_logger = logger;
        }

        public virtual void GetResults(string keyword, int resultCount)
        {
            try
            {
                Values = new ObservableCollection<INewsResult>();

                var client = new Google.API.Search.GnewsSearchClient("");
                var results = client.Search(keyword, resultCount);

                foreach (Google.API.Search.INewsResult res in results)
                {
                    var result = (INewsResult)_container.Resolve(typeof(INewsResult));
                    result.DateTime = res.PublishedDate;
                    result.Title = res.Title;
                    result.Content = res.Content;
                    result.Url = res.Url;
                    result.Publisher = res.Publisher;
                    
                    Values.Add(result);
                }
            }
            catch (Exception e)
            {
                //_logger.Log(e.Message, Category.Exception, Priority.High);
            }
        }

        private void NotifyPropertyChanged(string info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
    }
}
